<template>
	<view class="blood-pressure-container">
		<!-- 最新血压 -->
		<view class="latest-box">
			<view class="section-header">
				<text>最新血压</text>
				<view class="view-more" style="z-index: 99;" @click="toMore">查看更多 ></view>
			</view>
			<view class="blood-pressure-value" v-if="records.length>0">
				<text class="pressure-number">{{records[0].systolicPressure}}/{{records[0].diastolicPressure}}</text>
				<text class="pressure-unit">mmHg</text>
			</view>
			<view class="measure-time" v-if="records.length>0">测量日期：{{records[0].measuredTime}}
				<span style="padding-left: 10px;" :style="{color: records[0].color}">{{ records[0].tag}}</span>
			</view>
		</view>

		<!-- 趋势 -->
		<view class="trend-box">
			<view class="section-header">
				<text>血压趋势</text>
				<text class="view-more">查看详情 ></text>
			</view>
			<view class="date-filter">
				<view class="filter-buttons">
					<text :class="{ active: activeFilter === 'week7' }" @click="switchFilter('week7')">近七天</text>
					<text :class="{ active: activeFilter === 'day' }" @click="switchFilter('day')">日</text>
					<text :class="{ active: activeFilter === 'week' }" @click="switchFilter('week')">周</text>
					<text :class="{ active: activeFilter === 'month' }" @click="switchFilter('month')">月</text>
				</view>
				<view class="date-picker-range">
					<picker mode="date" :value="startDate" @change="onStartDateChange">
						<text>{{startDate}}</text>
					</picker>
					<text class="separator">至</text>
					<picker mode="date" :value="endDate" @change="onEndDateChange">
						<text>{{endDate}}</text>
					</picker>
				</view>
			</view>
			<view class="chart-container">
				<qiun-data-charts type="line" :opts="trendOpts" :chartData="trendData" />
			</view>
			<view class="legend">
				<view class="legend-item">
					<view class="legend-label">
						<view class="dot normal"></view>
						<text>正常</text>
					</view>
					<text class="count">{{statistics.normalCount}}次</text>
				</view>
				<view class="legend-item">
					<view class="legend-label">
						<view class="dot high"></view>
						<text>偏高</text>
					</view>
					<text class="count high">{{statistics.highCount}}次</text>
				</view>
				<view class="legend-item">
					<view class="legend-label">
						<view class="dot low"></view>
						<text>偏低</text>
					</view>
					<text class="count low">{{statistics.lowCount}}次</text>
				</view>
			</view>
		</view>

		<!-- 数据记录 -->
		<view class="data-records">
			<view class="section-header">
				<text>数据记录</text>
			</view>
			<view class="record-item" v-for="(item, index) in records" :key="index" v-if="records.length>0">
				<view class="record-main">
					<text class="value">血压：{{item.systolicPressure}}/{{item.diastolicPressure}}mmHg</text>
					<text>状态：<text :style="{color: item.color}">{{ item.tag}}</text></text>
				</view>
				<view class="record-sub">
					<text>测量时间：{{ item.measuredTime}}</text>
					<text>上传方式：{{ item.sourceName }}</text>
				</view>
				<view class="record-time">测量时间：{{item.measuredTime}}</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-button">
			<text class="bind-device">绑定设备</text>
			<button class="add-record" @click="addRecord">添加血压</button>
		</view>
	</view>
</template>

<script>
	import {
		listBloodPressure,
		queryTrendListBP,
		statisticsExceBP,
		queryBloodPressureTypeList
	} from '@/api/healthData/everyBloodPressure.js'
	export default {
		data() {
			return {
				userId: this.$store.state.user.userId,
				records: [],
				dictsList: [],
				targetId: '',
				startDate: (() => {
					const d = new Date();
					d.setDate(d.getDate() - 6);
					return this.formatDate(d)
				})(),
				endDate: this.formatDate(new Date()),
				statistics: {
					normalCount: 0,
					highCount: 0,
					lowCount: 0
				},
				trendOpts: {
					color: ['#4cd8aa', '#ff4d4f', '#1890ff'],
					padding: [15, 15, 0, 15],
					enableScroll: false,
					legend: false,
					xAxis: {
						disableGrid: true,
						fontSize: 12,
						color: '#666'
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 4,
						data: [{
							min: 40,
							max: 200,
							format: 'val'
						}]
					},
					extra: {
						line: {
							type: 'straight',
							width: 2
						},
						area: {
							opacity: 0.2,
							gradient: true
						},
						point: {
							size: 3,
							borderWidth: 2,
							strokeColor: '#FFFFFF'
						}
					}
				},
				trendData: {
					categories: [],
					series: [{
						name: '收缩压',
						data: []
					}, {
						name: '舒张压',
						data: []
					}]
				},
				records: [],
				activeFilter: 'week7'
			}
		},
		onLoad(options) {
			this.targetId = options.targetId
			this.queryTypeList()
		},
		onShow() {
			this.fetchList()
			this.fetchTrend()
		},
		computed: {
			latestText() {
				if (this.records.length === 0) return '--/--'
				const r = this.records[0]
				return `${r.systolic}/${r.diastolic}`
			}
		},
		methods: {
			addRecord() {
				uni.navigateTo({
					url: '/subPackage_1/pages/index/healthData/add-blood-pressure?targetId=' + this.targetId
				})
			},
			toMore() {
				uni.navigateTo({
					url: '/subPackage_1/pages/index/healthData/more-blood-pressure'
				})
			},
			formatDate(date) {
				const y = date.getFullYear();
				const m = String(date.getMonth() + 1).padStart(2, '0');
				const d = String(date.getDate()).padStart(2, '0');
				return `${y}-${m}-${d}`
			},
			onStartDateChange(e) {
				this.startDate = e.detail.value;
				this.fetchTrend()
			},
			onEndDateChange(e) {
				this.endDate = e.detail.value;
				this.fetchTrend()
			},
			switchFilter(type) {
				this.activeFilter = type;
				const today = new Date();
				if (type === 'week7') {
					const s = new Date(today);
					s.setDate(today.getDate() - 6);
					this.startDate = this.formatDate(s);
					this.endDate = this.formatDate(today);
				}
				if (type === 'day') {
					this.startDate = this.formatDate(today);
					this.endDate = this.formatDate(today);
				}
				if (type === 'week') {
					const mon = new Date(today);
					mon.setDate(today.getDate() - today.getDay() + (today.getDay() === 0 ? -6 : 1));
					const sun = new Date(mon);
					sun.setDate(mon.getDate() + 6);
					this.startDate = this.formatDate(mon);
					this.endDate = this.formatDate(sun);
				}
				if (type === 'month') {
					const ms = new Date(today.getFullYear(), today.getMonth(), 1);
					this.startDate = this.formatDate(ms);
					this.endDate = this.formatDate(today);
				}
				this.fetchTrend()
			},
			fetchList() {
				listBloodPressure({
					userId: this.userId
				}).then(res => {
					if (res.rows && res.rows.length > 0) {
						// 只保留最新的两条记录
						this.records = res.rows.slice(0, 2)
					}
				})
			},
			fetchTrend() {
				queryTrendListBP({
					startDate: this.startDate,
					endDate: this.endDate,
					userId: this.userId
				}).then(res => {
					const categories = (res.data || []).map(i => {
						const d = new Date(i.measuredTime);
						return `${(d.getMonth()+1).toString().padStart(2,'0')}-${d.getDate().toString().padStart(2,'0')}`
					})
					const systolic = (res.data || []).map(i => parseInt(i.systolic))
					const diastolic = (res.data || []).map(i => parseInt(i.diastolic))
					this.trendData = {
						categories,
						series: [{
							name: '收缩压',
							data: systolic
						}, {
							name: '舒张压',
							data: diastolic
						}]
					}
					this.statisticsExce()
				})
			},
			statisticsExce() {
				statisticsExceBP({
					startDate: this.startDate,
					endDate: this.endDate,
					userId: this.userId
				}).then(res => {
					if (res.code === 200 && res.data) {
						this.statistics.normalCount = res.data.正常|| 0;
						this.statistics.highCount =(res.data.高血压前期?Number(res.data.高血压前期):0)+ (res.data.一级高血压?Number(res.data.一级高血压):0)+(res.data.二级高血压?Number(res.data.二级高血压):0)+(res.data.三级高血压?Number(res.data.三级高血压):0	)  || 0;
						this.statistics.lowCount = res.data.低血压 || 0
					}
				})
			},
			queryTypeList() {
				queryBloodPressureTypeList({
					targetId: this.targetId
				}).then(res => {
					this.dictsList = res.data || []
				})
			}
		}
	}
</script>

<style scoped>
	.blood-pressure-container {
		min-height: 100vh;
		background: #fff;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
	}

	.view-more {
		color: #7BC691;
		font-size: 13px;
	}

	.latest-box .section-header {
		position: relative;
		overflow: hidden;
	}

	.latest-box .section-header::after {
		content: '';
		position: absolute;
		top: 26rpx;
		left: 10rpx;
		width: 100%;
		height: 50rpx;
		background-image: url('https://www.ruilongan.com/profile/upload/2025/06/27/路径@2x_20250627113158A059.png');
		background-repeat: no-repeat;
		background-position: left top;
		background-size: contain;
	}

	.latest-box .section-header text:first-child {
		position: relative;
		z-index: 2;
		font-size: 38rpx;
		font-weight: 500;
		color: #000;
	}

	.latest-box .section-header .view-more {
		position: relative;
		z-index: 2;
	}

	.trend-box .section-header,
	.data-records .section-header {
		position: relative;
		overflow: hidden;
	}

	.trend-box .section-header::after,
	.data-records .section-header::after {
		content: '';
		position: absolute;
		top: 26rpx;
		left: 10rpx;
		width: 100%;
		height: 50rpx;
		background-image: url('https://www.ruilongan.com/profile/upload/2025/06/27/路径@2x_20250627113158A059.png');
		background-repeat: no-repeat;
		background-position: left top;
		background-size: contain;
	}

	.trend-box .section-header text:first-child,
	.data-records .section-header text:first-child {
		position: relative;
		z-index: 2;
		font-size: 38rpx;
		font-weight: 500;
		color: #000;
	}

	.trend-box .section-header .view-more,
	.data-records .section-header .view-more {
		position: relative;
		z-index: 2;
	}

	.latest-box {
		padding: 0 15px 20px;
		position: relative;
		overflow: hidden;
	}

	.blood-pressure-value {
		text-align: center;
		margin: 20px 0 10px 0;
		position: relative;
		z-index: 2;
	}

	.pressure-number {
		font-size: 36px;
		font-weight: bold;
		color: #333;
		line-height: 1;
	}

	.pressure-unit {
		font-size: 14px;
		color: #666;
		margin-left: 8px;
	}

	.measure-time {
		text-align: center;
		color: #abaeaf;
		font-size: 13px;
		margin-top: 15px;
		position: relative;
		z-index: 2;
	}

	.trend-box {
		padding: 24rpx;
	}

	.date-filter {
		display: flex;
		flex-direction: column;
		padding: 0 15px;
		margin-bottom: 10px;
		border-bottom: 1px solid #f5f5f5;
	}

	.filter-buttons {
		display: flex;
		align-items: center;
		height: 40px;
	}

	.filter-buttons text {
		margin-right: 8px;
		color: #666;
		font-size: 13px;
		padding: 4px 12px;
		border-radius: 15px;
		background-color: #F5F5F5;
	}

	.filter-buttons .active {
		color: #fff;
		background-color: #4CD080;
	}

	.date-picker-range {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 8px 0;
		width: 100%;
	}

	.date-picker-range picker {
		flex: 0 0 auto;
		width: 95px;
	}

	.date-picker-range picker text {
		display: block;
		text-align: center;
		padding: 4px 0;
		font-size: 12px;
		color: #666;
		background: #F5F5F5;
		border-radius: 4px;
	}

	.date-picker-range .separator {
		padding: 0 4px;
		color: #666;
		font-size: 12px;
	}

	.chart-container {
		height: 220px;
		padding: 10px;
	}

	.legend {
		display: flex;
		justify-content: center;
		padding: 10px 0;
		border-top: 1px solid #f5f5f5;
		background-color: #FBFBFD;
		border-radius: 8px;
		margin: 0 15px;
	}

	.legend-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 0;
		font-size: 12px;
		color: #666;
		padding: 8px 12px;
		flex: 1;
		position: relative;
	}

	.legend-item:not(:last-child)::after {
		content: '';
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 1px;
		height: 60%;
		background-color: #E0E0E0;
	}

	.legend-label {
		display: flex;
		align-items: center;
		margin-bottom: 4px;
	}

	.count {
		font-size: 11px;
		color: #999;
	}

	.count.normal {
		color: #333;
	}

	.count.high {
		color: #ff8080;
	}

	.count.low {
		color: #1b76ff;
	}

	.dot {
		width: 12px;
		height: 8px;
		border-radius: 2px;
		margin-right: 4px;
	}

	.dot.normal {
		background: #10c558;
	}

	.dot.high {
		background: #ff8080;
	}

	.dot.low {
		background: #1b76ff;
	}

	.data-records {
		padding: 24rpx;
		padding-bottom: 120rpx;
	}

	.record-item {
		padding: 15px;
		border-bottom: 1px solid #f5f5f5;
	}

	.record-main {
		display: flex;
		justify-content: space-between;
		margin-bottom: 8px;
		font-size: 14px;
	}

	.record-sub {
		display: flex;
		justify-content: space-between;
		color: #666;
		font-size: 13px;
		margin-bottom: 5px;
	}

	.record-time {
		color: #999;
		font-size: 12px;
	}

	.bottom-button {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 15px;
		background: #fff;
		box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.bind-device {
		padding-left: 40rpx;
		color: #4CD080;
		font-size: 28rpx;
	}

	.add-record {
		background: #10c558;
		color: #fff;
		border-radius: 10px;
		font-size: 15px;
		height: 44px;
		line-height: 44px;
		border: none;
		width: 430rpx;
		margin: 0;
	}
</style>